package com.nsgf.library.ui.monitoring;

import static com.nsgf.library.utils.Utils.generateRandomColor;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.ChartDataBean;
import com.nsgf.library.data.bean.DisplacementBean;
import com.nsgf.library.data.bean.MonitorBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNsgfMonitoringGnssBinding;
import com.nsgf.library.databinding.ItemChartsTitleBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.SimpleDataBindingPositionAdapter;
import com.nsgf.library.ui.adapter.ViewHolder;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.utils.Utils;
import com.nsgf.library.widget.DisplacementMarkerListView;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.nsgf.library.widget.prckerview.TimePickerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * GNSS监测
 */
public class GNSSLandscapeActivity extends BaseActivity {

    StateHolder mStates;

    private AccountRequester mAccountRequester;

    private int type = 5;//水平位移量分布图  5N方向 6E方向

    private String monitorType = "";//

    private String JsonObject;//接口参数
    private List<DisplacementBean> list = new ArrayList<>();

    @Override
    protected void initViewModel() {

        mStates = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new SimpleDataBindingPositionAdapter<ChartDataBean,
                ItemChartsTitleBinding>(this, R.layout.item_charts_title,
                new DiffUtil.ItemCallback() {
                    @Override
                    public boolean areItemsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                        return false;
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                        return false;
                    }
                }) {
            @Override
            protected void onBindItem(ItemChartsTitleBinding binding, ChartDataBean item, ViewHolder holder, int position) {
                binding.setVm(item);
                setOnItemClickListener((viewId, item1, position1) -> {
                    mStates.chartNEDataBean.get().get(position1).setChartLineDataSet(!item1.isChartLineDataSet());
                    if (type == 5 || type == 8)
                        invalidate();
                    else
                        invalidateNAndE();
                    notifyItemChanged(position1);
                });
            }
        };
        return new DataBindingConfig(R.layout.activity_nsgf_monitoring_gnss, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter);
    }

    private ActivityNsgfMonitoringGnssBinding mBinding;

    protected Typeface tfRegular;


    JSONArray points = null;
    JSONArray times = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityNsgfMonitoringGnssBinding) getBinding();

        getLifecycle().addObserver(mAccountRequester);
        mStates.titleBar.set(getIntent().getStringExtra("title"));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mBinding.recyclerViewNE.setLayoutManager(layoutManager);
        mBinding.recyclerViewNE.setItemAnimator(null);
        mBinding.titlebar.titleBarRoot.setTextColor(getResources().getColor(R.color.color_1D2129));
        mBinding.titlebar.titleBarBack.setImageResource(R.drawable.ic_nsgf_back);
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_chart_min_landscape);
        mBinding.titlebar.titleBarClear.setOnClickListener(v -> finish());
        JsonObject = getIntent().getStringExtra("JsonObject");
        tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        type = getIntent().getIntExtra("type", 5);
        monitorType = getIntent().getStringExtra("monitorType");
        indexSection = getIntent().getIntExtra("indexSection", 0);
        calendarStarTime.setTimeInMillis(getIntent().getLongExtra("calendarStarTime", 0));
        calendarNEStarTime.setTimeInMillis(getIntent().getLongExtra("calendarNEStarTime", 0));
        calendarNEEndTime.setTimeInMillis(getIntent().getLongExtra("calendarNEEndTime", 0));
        mStates.startTime.set(getIntent().getStringExtra("startTime"));
        mStates.NEStartTime.set(Kits.Date.getYmd(calendarNEStarTime.getTimeInMillis()));
        mStates.NEEndTime.set(Kits.Date.getYmd(calendarNEEndTime.getTimeInMillis()));

        mBinding.chart.setNoDataText("暂无相关数据");

        if (type == 5 || type == 8) {
            mBinding.llGnssTime.setVisibility(View.VISIBLE);
        } else {
            mBinding.llGnssRangDate.setVisibility(View.VISIBLE);
        }

        switch (type) {
            case 5:
            case 8:
                mAccountRequester.getGNSSDisplacementDist(JsonObject.toString());
                break;
            case 6:
            case 7:
            case 9:
                mAccountRequester.getGNSSProcessLine(JsonObject.toString());
                break;
        }
        mAccountRequester.getDisplacementResult().observe(this, new Observer<ResponseStatus<List<DisplacementBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<DisplacementBean>> listResponseStatus) {

                if (listResponseStatus.getResponseCode() == 200) {

                    mStates.chartNEDisplacementBean.set((ArrayList<DisplacementBean>) listResponseStatus.getData());
                    mStates.chartNEDataBean.get().clear();
                    mBinding.chart.setData(null);
                    mBinding.chart.highlightValue(null);
                    mBinding.chart.invalidate();

                    if (listResponseStatus.getData().isEmpty()) {
                        mAdapter.submitList(new ArrayList<>());
                        return;
                    }

                    if (type == 5) {
                        for (int i = 0; i < 2; i++) {
                            ChartDataBean bean = new ChartDataBean();
                            bean.setChartTitles(i == 0 ? "N方向" : "E方向");
                            bean.setColor(generateRandomColor(i));
                            bean.setChartLineDataSet(true);
                            mStates.chartNEDataBean.get().add(bean);
                        }
                    } else if (type == 8) {

                        ChartDataBean bean = new ChartDataBean();
                        bean.setChartTitles("累计位移量");
                        bean.setColor(generateRandomColor(0));
                        bean.setChartLineDataSet(true);
                        mStates.chartNEDataBean.get().add(bean);
                    }

                    mAdapter.submitList(mStates.chartNEDataBean.get());
                    initLineDataSet(listResponseStatus.getData());
                    setData(listResponseStatus.getData());

                } else {
                    ToastUtils.showShortToast(listResponseStatus.getMsg());
                }

            }
        });


        mAccountRequester.getStringResult().observe(this, objectResponseStatus -> {


            if (objectResponseStatus.getResponseCode() == 200) {

                String json = new Gson().toJson(objectResponseStatus.getData());
                JSONObject jsonObject = null;
                JSONObject dataList = null;

                try {
                    jsonObject = new JSONObject(json);
                    points = new JSONArray(jsonObject.get("points").toString());
                    dataList = new JSONObject(jsonObject.get("dataList").toString());
                    times = new JSONArray(jsonObject.get("times").toString());
                    Iterator<String> keys = dataList.keys();

                    int i = 0;
                    mStates.chartNEDataBean.get().clear();
                    list.clear();
                    while (keys.hasNext()) {
                        DisplacementBean displacementBean = new DisplacementBean();
                        String key = keys.next();
                        displacementBean.setTestPoint(key);
                        ChartDataBean bean = new ChartDataBean();
                        bean.setChartTitles(key);
                        bean.setColor(generateRandomColor(i));
                        bean.setChartLineDataSet(true);
                        mStates.chartNEDataBean.get().add(bean);
                        Type listType = new TypeToken<List<DisplacementBean>>() {
                        }.getType();
                        List<DisplacementBean> info = new Gson().fromJson(dataList.get(key).toString(), listType);
                        displacementBean.setBeanList(info);
                        list.add(displacementBean);
                        i++;
                    }

                    //每次载入新数据需情况原有数据 避免出现空指针
                    mBinding.chart.setData(null);
                    mBinding.chart.highlightValue(null);
                    mBinding.chart.invalidate();

                    if (mStates.chartNEDataBean.get().isEmpty()) {
                        mAdapter.submitList(new ArrayList<>());
                        return;
                    }

                    initLineDataSetNAndE(mBinding.chart);
                    setNAndEData(mBinding.chart);
                    mAdapter.submitList(mStates.chartNEDataBean.get());
                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ToastUtils.showShortToast(objectResponseStatus.getMsg());
            }

        });

        mBinding.ivNsgfScale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.llNsgfIndicate.setVisibility(View.GONE);
            }
        });

        getController().displayLoading();
        mAccountRequester.getSectionTm(UserInfo.getInstance().getProjectCode(),
                "monitor.obj.1",
                monitorType);

        mAccountRequester.getMonitorBeanResult().observe(this, responseStatus -> {

            getController().dismissLoading();
            if (responseStatus.getResponseCode() == 200) {

                monitorBeanState = responseStatus.getData();
                if (savedInstanceState == null) {

                    section = new JsonArray();

                    if (!responseStatus.getData().getSection().isEmpty()) {
                        JsonObject jsonObjectSection = new JsonObject();
                        jsonObjectSection.addProperty("sectionName", responseStatus.getData()
                                .getSection().get(indexSection).getSectionName());
                        jsonObjectSection.addProperty("type", responseStatus.getData()
                                .getSection().get(indexSection).getType());
                        section.add(jsonObjectSection);
                        mStates.sectionName.set(responseStatus.getData().getSection().get(indexSection).getSectionName());
                    }

                }

                Glide.with(this)
                        .load(APIs.BASE_URL_IMG
                                + responseStatus.getData().getFilesSrc())
                        .thumbnail(0.1f)
                        .dontAnimate()
                        .dontTransform()
                        .override(800)
                        .placeholder(R.drawable.__picker_ic_photo_black_48dp)
                        .error(R.drawable.__picker_ic_broken_image_black_48dp)
                        .into(mBinding.ivNsgfScale);

            } else {
                ToastUtils.showLongToast(responseStatus.getMsg());
            }
        });

    }


    private SimpleDataBindingPositionAdapter<ChartDataBean, ItemChartsTitleBinding> mAdapter;

    DisplacementMarkerListView mv;

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSet(List<DisplacementBean> list) {

        {   // // Chart Style // //

            // background color
            mBinding.chart.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            mBinding.chart.setDrawGridBackground(false);
            //是否显示边界
            mBinding.chart.setDrawBorders(false);
            // disable description text
            mBinding.chart.getDescription().setEnabled(false);

            // enable touch gestures
            mBinding.chart.setTouchEnabled(true);

            // enable scaling and dragging
            mBinding.chart.setDragEnabled(true);
            mBinding.chart.setScaleEnabled(true);
            // mBinding.chart.setScaleXEnabled(true);
            // mBinding.chart.setScaleYEnabled(true);

            // force pinch zoom along both axis
            mBinding.chart.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = mBinding.chart.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setAxisMinimum(0f);
            mBinding.chart.moveViewToX(0);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.enableAxisLineDashedLine(10f, 10f, 0f);
            xAxis.setTextColor(getResources().getColor(R.color.color_86909C));
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (list.isEmpty() || value < 0)
                        return list.get(0).getTestPoint();
                    if ((int) value >= list.size())
                        return list.get(list.size() - 1).getTestPoint();
                    return list.get((int) value).getTestPoint();
                }
            });
            xAxis.setLabelCount(15, false);
        }

        YAxis yAxis = mBinding.chart.getAxisLeft();

        // disable dual axis (only use LEFT axis)
        mBinding.chart.getAxisRight().setEnabled(false);

        yAxis.setTextColor(getResources().getColor(R.color.color_86909C));
        yAxis.setLabelCount(10, false);
        mBinding.chart.setExtraLeftOffset(10f);
        // horizontal grid lines
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        // create marker to display box when values are selected
        if (null != list) {
            mv = new DisplacementMarkerListView(this, list, mStates.chartNEDataBean.get(), type);
            mv.setChartView(mBinding.chart);
            mBinding.chart.setMarker(mv);
            mBinding.chart.invalidate();
        }

        {   // // Create Limit Lines // //
            LimitLine llYAxis = new LimitLine(0, "");
            llYAxis.setLineWidth(0.5f);
//            llYAxis.enableDashedLine(10f, 10f, 0f);
            llYAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            llYAxis.setLineColor(getResources().getColor(R.color.color_86909C));
            llYAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);

            yAxis.addLimitLine(llYAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        mBinding.chart.animateX(500);
        mBinding.chart.animateY(500);

        // get the legend (only possible after setting data)
        Legend l = mBinding.chart.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        l.setEnabled(false);
        while (!mBinding.chart.isFullyZoomedOut()) {

            mBinding.chart.zoomOut();
        }


    }


    List<LineDataSet> lineDataSet = new ArrayList<>();
    List<LineDataSet> lineDataSetNEDirection = new ArrayList<>();//E B方向累计位移量

    /**
     * 数据加载
     */
    private void setData(List<DisplacementBean> list) {


        LineData lineData = new LineData();
        lineDataSet.clear();
        if (list.isEmpty()) {
            mBinding.chart.setData(null);
            return;
        }
        for (int j = 0; j < mStates.chartNEDataBean.get().size(); j++) {

            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Entry entry;
                if (type == 5) {
                    if (j == 0)
                        entry = new Entry(i, list.get(i).getDisplacementN());
                    else
                        entry = new Entry(i, list.get(i).getDisplacementE());
                } else
                    entry = new Entry(i, list.get(i).getDisplacement());
                entries.add(entry);
            }

            // 每一个LineDataSet代表一条线
            LineDataSet value = new LineDataSet(entries, mStates.chartNEDataBean.get().get(j).getChartTitles());
            value.setColor(mStates.chartNEDataBean.get().get(j).getColor());
            value.setCircleColor(mStates.chartNEDataBean.get().get(j).getColor());
            value.setLineWidth(1f);
            value.setCircleRadius(1f);
            value.setDrawCircles(false);
            value.setDrawValues(false);
            //设置曲线值的圆点是实心还是空心
            value.setDrawCircleHole(false);
            value.setValueTextSize(10f);
            value.enableDashedHighlightLine(10f, 5f, 0f);
            //设置折线图填充
//        lineDataSet.setDrawFilled(true);
            value.setFormLineWidth(0f);
            value.setFormSize(15.f);
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            value.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            value.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return mBinding.chart.getAxisLeft().getAxisMinimum();
                }
            });
            lineDataSet.add(value);
            lineData.addDataSet(value);
        }
        mBinding.chart.setData(lineData);

        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chart.getAxisLeft().setAxisMaximum(max);
        mBinding.chart.getAxisLeft().setAxisMinimum(min);

    }


    private void invalidate() {
        if (lineDataSet.isEmpty()) {
            return;
        }
        mBinding.chart.highlightValue(null);
        mBinding.chart.invalidate();
        LineData lineData = new LineData();
        for (int i = 0; i < mStates.chartNEDataBean.get().size(); i++) {
            if (mStates.chartNEDataBean.get().get(i).isChartLineDataSet()) {
                lineData.addDataSet(lineDataSet.get(i));
            }
        }

        if (lineData.getDataSets().isEmpty()) {
            mBinding.chart.setData(null);
            mBinding.chart.invalidate();
            return;
        }

        mBinding.chart.setData(lineData);
        mv.setChartDataBeans(mStates.chartNEDataBean.get());
        mBinding.chart.setMarker(mv);
        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chart.getAxisLeft().setAxisMaximum(max);
        mBinding.chart.getAxisLeft().setAxisMinimum(min);
        mBinding.chart.invalidate();
        mAdapter.notifyDataSetChanged();

    }


    private int indexSection = 0;


    private Calendar calendarStarTime = Calendar.getInstance();
    private Calendar calendarNEStarTime = Calendar.getInstance();
    private Calendar calendarNEEndTime = Calendar.getInstance();

    public class ClickProxy {

        public void openPreview() {

            mBinding.llNsgfIndicate.setVisibility(View.VISIBLE);
        }

        /**
         * 筛选断面
         */
        public void screenSection() {

            OptionsPickerView<MonitorBean.SectionBean> mOptionsPickerView =
                    new OptionsPickerView
                            .Builder(GNSSLandscapeActivity.this, (options1,
                                                                  options2,
                                                                  options3,
                                                                  v) -> {
                        mStates.sectionName.set(monitorBeanState.getSection().get(options1)
                                .getPickerViewText());
                        indexSection = options1;
                        section = new JsonArray();

                        JsonObject jsonObject = new JsonObject();
                        jsonObject.addProperty("sectionName", monitorBeanState.getSection()
                                .get(options1).getSectionName());
                        jsonObject.addProperty("type", monitorBeanState.getSection().get(options1).getType());
                        section.add(jsonObject);
                        switch (type) {
                            case 5:
                            case 8:
                                getGNSSDisplacementDist();
                                break;
                            case 6:
                            case 7:
                            case 9:
                                getGNSSProcessLine();
                                break;
                        }
                    }).build();
            mOptionsPickerView.setPicker(monitorBeanState.getSection());
            mOptionsPickerView.setSelectOptions(indexSection);
            mOptionsPickerView.show();
        }

        public void screenTestTime() {

            boolean[] type = new boolean[]{true, true, true, true, false, false};//显示类型 默认全部显示

            Calendar rangDateStart = Calendar.getInstance();
            rangDateStart.set(Calendar.YEAR, rangDateStart.get(Calendar.YEAR) - 10);
            TimePickerView mTimePickerView = new TimePickerView.Builder(GNSSLandscapeActivity.this, (date, v) -> {
                mStates.startTime.set(Kits.Date.getYmdh(date.getTime()) + ":00:00");
                calendarStarTime.setTimeInMillis(date.getTime());
                getGNSSDisplacementDist();
            }).isCyclic(false)
                    .setRangDate(rangDateStart, Calendar.getInstance())
                    .setType(type)
                    .setTitleText("选择时间")
                    .setDate(calendarStarTime)
                    .build();

            mTimePickerView.show();


        }


        public void screenNEStarTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示
            Calendar rangDateStart = Calendar.getInstance();
            rangDateStart.set(Calendar.YEAR, rangDateStart.get(Calendar.YEAR) - 10);
            TimePickerView mTimePickerView = new TimePickerView.Builder(GNSSLandscapeActivity.this,
                    (date, v) -> {
                        calendarNEStarTime.setTimeInMillis(date.getTime());
                        mStates.NEStartTime.set(Kits.Date.getYmd(calendarNEStarTime.getTimeInMillis()));
                        getGNSSProcessLine();
                    }).isCyclic(false)
                    .setRangDate(rangDateStart, calendarNEEndTime)
                    .setType(type)
                    .setTitleText("开始时间")
                    .setDate(calendarNEStarTime)
                    .build();

            mTimePickerView.show();


        }

        public void screenNEEndTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(GNSSLandscapeActivity.this, (date, v) -> {
                mStates.NEEndTime.set(Kits.Date.getYmd(date.getTime()));
                calendarNEEndTime.setTimeInMillis(date.getTime());
                getGNSSProcessLine();
            }).isCyclic(false)
                    .setRangDate(calendarNEStarTime, Calendar.getInstance())
                    .setType(type)
                    .setTitleText("结束时间")
                    .setDate(calendarNEEndTime)
                    .build();

            mTimePickerView.show();


        }

    }


    JsonArray section = new JsonArray();

    private MonitorBean monitorBeanState = new MonitorBean();//断面 测次 示意图
    JsonObject params = new JsonObject();

    private void getGNSSDisplacementDist() {
        params.addProperty("monitorCode", monitorBeanState.getMonitorCode());
        params.addProperty("monitorType", monitorType);
        params.add("section", section);
        params.addProperty("startTime", mStates.startTime.get());
        mAccountRequester.getGNSSDisplacementDist(params.toString());
    }

    private void getGNSSProcessLine() {
        params.addProperty("monitorCode", monitorBeanState.getMonitorCode());
        params.addProperty("monitorType", monitorType);
        params.add("section", section);
        params.addProperty("startTime", mStates.NEStartTime.get());
        params.addProperty("endTime", mStates.NEEndTime.get());
        mAccountRequester.getGNSSProcessLine(params.toString());

    }


    DisplacementMarkerListView mvNE;

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSetNAndE(LineChart chart) {

        {   // // Chart Style // //

            // background color
            chart.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            chart.setDrawGridBackground(false);
            //是否显示边界
            chart.setDrawBorders(false);
            // disable description text
            chart.getDescription().setEnabled(false);

            // enable touch gestures
            chart.setTouchEnabled(true);

            // enable scaling and dragging
            chart.setDragEnabled(true);
            chart.setScaleEnabled(true);
            // chart.setScaleXEnabled(true);
            // chart.setScaleYEnabled(true);

            // force pinch zoom along both axis
            chart.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setAxisMinimum(-1f);
            xAxis.setAxisMaximum(times.length());
            mBinding.chart.moveViewToX(0);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.enableAxisLineDashedLine(10f, 10f, 0f);
            xAxis.setTextColor(getResources().getColor(R.color.color_86909C));
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    try {
                        if ((int) value < 0)
                            return "";
                        if ((int) value >= times.length())
                            return "";
                        return Utils.formatTimeMD(times.get((int) value).toString());
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            xAxis.setLabelRotationAngle(-30f);
            xAxis.setLabelCount(8, false);
        }

        YAxis yAxis = chart.getAxisLeft();

        // disable dual axis (only use LEFT axis)
        chart.getAxisRight().setEnabled(false);

        yAxis.setTextColor(getResources().getColor(R.color.color_86909C));
        yAxis.setLabelCount(15, false);
        // horizontal grid lines
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        // create marker to display box when values are selected
        if (null != list) {
            mvNE = new DisplacementMarkerListView(GNSSLandscapeActivity.this,
                    list, mStates.chartNEDataBean.get(), true, type);
            mvNE.setChartView(chart);
            chart.setMarker(mvNE);

            chart.invalidate();
        }

        {   // // Create Limit Lines // //
            LimitLine llYAxis = new LimitLine(0, "");
            llYAxis.setLineWidth(0.5f);
//            llYAxis.enableDashedLine(10f, 10f, 0f);
            llYAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            llYAxis.setLineColor(getResources().getColor(R.color.color_86909C));
            llYAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);

            yAxis.addLimitLine(llYAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        chart.animateX(500);
        chart.animateY(500);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        l.setEnabled(false);
        while (!chart.isFullyZoomedOut()) {

            chart.zoomOut();
        }


    }

    private void setNAndEData(LineChart chart) {
        lineDataSetNEDirection.clear();

        if (list.isEmpty()) {
            mBinding.chart.setData(null);
            return;
        }
        LineData lineData = new LineData();
        for (int j = 0; j < list.size(); j++) {

            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < list.get(j).getBeanList().size(); i++) {
                Entry entry;
                if (type == 6) {
                    entry = new Entry(i, list.get(j).getBeanList().get(i).getDisplacementN());
                } else if (type == 7) {
                    entry = new Entry(i, list.get(j).getBeanList().get(i).getDisplacementE());
                } else if (type == 9) {
                    entry = new Entry(i, list.get(j).getBeanList().get(i).getDisplacement());
                } else
                    entry = new Entry(i, list.get(j).getBeanList().get(i).getDisplacement());
                entries.add(entry);
            }
            // 每一个LineDataSet代表一条线
            LineDataSet value = new LineDataSet(entries, list.get(j).getTestPoint());

            value.setColor(mStates.chartNEDataBean.get().get(j).getColor());
            value.setCircleColor(mStates.chartNEDataBean.get().get(j).getColor());
            value.setLineWidth(1f);
            value.setCircleRadius(1f);
            value.setDrawCircles(false);
            value.setDrawValues(false);
            //设置曲线值的圆点是实心还是空心
            value.setDrawCircleHole(false);
            value.setValueTextSize(10f);
            value.enableDashedHighlightLine(10f, 5f, 0f);
            //设置折线图填充
//        lineDataSet.setDrawFilled(true);
            value.setFormLineWidth(0f);
            value.setFormSize(15.f);
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            value.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            value.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return chart.getAxisLeft().getAxisMinimum();
                }
            });
            lineDataSetNEDirection.add(value);
            lineData.addDataSet(value);
        }
        chart.setData(lineData);

        float max = chart.getYMax() + ((chart.getYMax() - chart.getYMin()) / 3);
        float min = chart.getYMin() - ((chart.getYMax() - chart.getYMin()) / 3);

        chart.getAxisLeft().setAxisMaximum(max);
        chart.getAxisLeft().setAxisMinimum(min);

    }

    private void invalidateNAndE() {
        mBinding.chart.highlightValue(null);
        mBinding.chart.invalidate();
        LineData lineData = new LineData();
        for (int i = 0; i < lineDataSetNEDirection.size(); i++) {
            if (mStates.chartNEDataBean.get().get(i).isChartLineDataSet()) {
                lineData.addDataSet(lineDataSetNEDirection.get(i));
            }
        }

        if (lineData.getDataSets().isEmpty()) {
            mBinding.chart.setData(null);
            mBinding.chart.invalidate();
            return;
        }


        mBinding.chart.setData(lineData);
        mvNE.setChartDataBeans(mStates.chartNEDataBean.get());
        mBinding.chart.setMarker(mvNE);
        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chart.getAxisLeft().setAxisMaximum(max);
        mBinding.chart.getAxisLeft().setAxisMinimum(min);
        mBinding.chart.invalidate();

    }

}
